#include "stdafx.h"
#include "NetworkController.h"
#include "Client.h"
#include "Server.h"
#include "AvatarController.h"
#include "Input.h"
#include "Controller.h"
#include <Windows.h>
#include "NetworkGameMessages.h"

NetworkController::NetworkController(string ip, Model* model) {
	isServer = false;
	isClient = false;
	m_ip = ip;

	// if ip is localhost then create the server
	if(m_ip == "127.0.0.1") {
		createServer(model);
	}
	
	createClient(model);
}

void NetworkController::createClient(Model* model) {
	char str[512];
	char* maxPlayers = "10";

	char* serverPort = "1337";
	char* serverPassword = "hej";

	c = new Client();
	c -> createClient("10", model);
	c -> connect((char*)m_ip.c_str(), "1337", "hej");
	isClient = true;
}


void NetworkController::createServer(Model* model) {
	isServer = true;
	
	s = new Server();
	s->createServer("1337", "hej", "10", model);
}

void NetworkController::sendCommands(list<Command*> &commands) {
	if(c != NULL && !commands.empty()) {
		if(c->connected) {
			list<Command*>::iterator it;
		
			// Declaring the size of this commandlist
			int i = commands.size();
			RakNet::MessageID msg = NEW_COMMAND;
			bsOut.Write(msg);
			bsOut.Write((char*) &i, sizeof(int));

			for (it = commands.begin() ; it != commands.end() ; it++) {
				(*it)->save(bsOut);
			}
			c->client->Send(&bsOut,HIGH_PRIORITY,RELIABLE_ORDERED,0,c->serverAddress,false);
			bsOut.Reset();
		}
	}
}

bool NetworkController::update(float deltaTime) {
	if(isServer) {
		s->receivePackets();
	} 
	
	if(isClient) {
		if (c->connected) {
			c->receivePackets();
		}
	}

	return true;
}

void NetworkController::terminateServer() {
	s->terminateServer();
}

void NetworkController::terminateClient() {
	c->disconnect();
}